/**
 * 准备函数
 */
var operateRight = new Object();
$(document).ready(function() {
	// 加载权限
	loadRight();

	// 加载表格
	queryAgent();
	
	// 加载form模块
	layui.use(['form'], function() {
		$form = layui.form;
		// 版本创建
		$form.on('radio(cProxyType)', function(data) {
			if(data.value == "1"){
				$(".company-data").show();
				$(".personal-data").hide();
			}else{
				$(".company-data").hide();
				$(".personal-data").show();
			}
		});
		
		// 版本修改
		$form.on('radio(mProxyType)', function(data) {
			if(data.value == "1"){
				$(".company-data").show();
				$(".personal-data").hide();
			}else{
				$(".company-data").hide();
				$(".personal-data").show();
			}
		});
	});
	
	// 绑定函数
	$("#queryButton").bind("click", confirmQueryAgent);
	$("#createButton").bind("click", showCreateAgentDialog);
	$("#confirmCreateButton").bind("click", confirmCreateAgent);
	$("#confirmModifyButton").bind("click", confirmModifyAgent);
	$("#confirmSetAgentLogoButton").bind("click", confirmSetAgentLogo);
	$("#confirmResetPassword").bind("click", resetPassword);
});

/**
 * 加载权限
 */
function loadRight() {
	operateRight.oemCofing = $("#oemCofing").val();
	operateRight.modifyUserPwd = $("#modifyUserPwd").val();
	operateRight.modifyRight = $("#modify").val();
	operateRight.deleteRight = $("#delete").val();
}

/**
 * 查询
 */
function queryAgent(pageIndex, pageSize) {
	// 组装参数
	var data = {};
	var name = $.trim($("#name").val());
	if (name != "") {
		data['name'] = name;
	}
	var phone = $.trim($("#phone").val());
	if (phone != "") {
		data['phone'] = phone;
	}
	var status = $.trim($("#status").val());
	if (status != "") {
		data['status'] = status;
	}
	var provinceId = $.trim($("#provinceId").val());
	if (provinceId != "") {
		data['provinceId'] = provinceId;
	}
	var cityId = $.trim($("#cityId").val());
	if (cityId != "") {
		data['cityId'] = cityId;
	}
	var categoryId = $.trim($("#categoryId").val());
	if (categoryId != "") {
		data['categoryId'] = categoryId;
	}

	// 设置分页参数
	setPageIndex(data, pageIndex, pageSize);

	// 调用接口
	var response = callInterface("post", "agent/queryAgentCompany", data, false);
	if (response.code == 0) {
		// 清空表格及分页
		$("#agentTable tr:not(:first)").remove();
		$("#pageDiv").html("");

		var count = response.data.totalCount;
		if (count == null || count == 0) {
			var cols = $("#agentTable").find("tr:first th");
			$('#agentTable').append("<tr><td colspan='" + cols.length + "'>无数据!</td></tr>");
			return false;
		}
		var list = response.data.list;
		if (list != null && list.length > 0) {
			
			for ( var i in list) {
				
				var trHtml = "<tr>";
				trHtml += "<td align='center'><a href='javascript:showAgentDetail(" + list[i].id + ");'>" + list[i].name + "</a></td>";
				trHtml += "<td align='center'>" + (list[i].proxyType == "1"?"公司":"个人") + "</td>";
				trHtml += "<td align='center'>" + (list[i].proxyType == "1"?list[i].contacts:'--') + "</td>";
				trHtml += "<td align='center'>" + list[i].telephone + "</td>";
				trHtml += "<td align='center'>" + list[i].positionLimit + "</td>";
				trHtml += "<td align='center'>" + Utils.convertNull(list[i].categoryName) + "</td>";
				var areaText = "";
				if(Utils.isNotNull(list[i].provinceName) && Utils.isNotNull(list[i].cityName)){
					areaText = list[i].provinceName + "-" + list[i].cityName;
				}
				trHtml += "<td align='center'>" + areaText + "</td>";
				trHtml += "<td align='center'><input id='agent_status_"+list[i].id+"' class='ace ace-switch' type='checkbox' "+ 
					(list[i].status == 1? 'checked': '')+" onclick='modifyAgentStatus(" + list[i].id + ");' /> <span class='lbl'></span></td>";
				trHtml += "<td align='center'>" + list[i].createdTime + "</td>";
				trHtml += "<td align='center' style='width:260px;' class='operationColumn'>";
				if(operateRight.modifyRight == 1) {
					trHtml += '<a class="edit" href="javascript:showModifyAgentDialog(' + list[i].id + ');">编辑</a>&nbsp;&nbsp;';
				}
				if(operateRight.oemCofing == 1) {
					trHtml += '<a class="copy" href="javascript:showOemDialog('+list[i].id +',\''+list[i].name+'\');">OEM配置</a>&nbsp;&nbsp;';
				}
				if (operateRight.modifyUserPwd == 1) {
					trHtml += '<a href="javascript:void(0);" class="add" onclick="showResetPasswordDialog(\''
						+ list[i].id + '\' , \'' + list[i].telephone + '\');">重置密码</a>&nbsp;&nbsp;';
				}
				trHtml += "</td>";
				trHtml += "</tr>";

				// 动态添加一行
				$('#agentTable').append(trHtml);
			}
		}

		// 调用分页
		layui.use(['laypage'], function() {
			var laypage = layui.laypage;
			laypage.render({
				elem : 'pageDiv',
				// pages : pages,
				curr : pageIndex || 1, // 当前页
				count : count,
				limit : pageSize,
				skip : true, // 是否开启跳页
				layout : ['count', 'prev', 'page', 'next', 'limit', 'skip'],
				groups : 5, // 连续显示分页数
				jump : function(obj, first) {
					if (!first) {
						queryAgent(obj.curr, obj.limit);
					}
				}
			});
		});
	}else {
		showErrorMsg(response.code, response.message);
	}
}

/**
 * 确认查询
 */
function confirmQueryAgent() {
	queryAgent();
}

/**
 * 显示OEM设置
 * 
 * @param id
 * @param name
 */
function showOemDialog(id, name){
	// 显示对话框
	$("#setAgentLogoDialog").modal({
		backdrop : 'static',
		keyboard : false,
		show : true
	});
	$('#setAgentLogoForm')[0].reset();
	$('#mId').val(id);
	$('#sAgentName').html(name);
	
	// 调用接口
	var response = callInterface("post", "agent/getAgentOEM", {
		"id" : id
	}, false);
	if (response.code == 0) {
		var data = response.data;
		if (data != null) {
			$("#mDomainName").val(data.domain);
			$("#mWebsiteTitle").val(data.websiteTitle);
			if( Utils.isNotNull(data.logo) ){
				// 初始化预览数据
				getImgPreHtml("mLogo", fuIndex++, "mLogoDiv", true, null, data.logo);
				$("#mLogo").attr("data-url",data.logo);
			}else{
				// 初始化文件选择相关
				$("#mLogo").attr("data-url","");
				var objIB = document.getElementById('mLogo'); 
				objIB.outerHTML = objIB.outerHTML;
				$("#mLogoDiv").html("");
			}
		}
	}
}

/**
 * 确认设置logo和域名
 */
function confirmSetAgentLogo(){
	// 获取参数
	var data = {};
	data['id'] = $('#mId').val();
	
	var domainName = $.trim($('#mDomainName').val());
	if (Utils.isNull(domainName)) {
		showAlert("平台域名不能为空!");
		return false;
	}
	data['domain'] = domainName;
	var title = $.trim($('#mWebsiteTitle').val());
	if (Utils.isNull(title)) {
		showAlert("平台名称不能为空!");
		return false;
	}
	data['websiteTitle'] = title;
	
	var logo = $("#mLogo").attr("data-url");
	if(Utils.isNull(logo)){
		showAlert("请上传平台Logo!");
		return false;
    }else{
    	data['logo'] = logo;
    }
	
	// 调用接口
	var response = callInterface("post", "agent/createAgentOEM", data,
			false);
	if (response.code == 0) {
		showMsg('操作成功!');
		
		// 关闭对话框
		$('#setAgentLogoDialog').modal("hide");
	} else {
		showErrorMsg(response.code, response.message);
	}
	return false;
}

/**
 * 显示创建对话框
 */
function showCreateAgentDialog() {
	$("#createAgentDialog").modal({
		backdrop : 'static',
		keyboard : false,
		show : true
	});
	$('#addAgentForm')[0].reset();
	initCreateData();
	updateLayuiForm();
}

// 初始化创建数据
function initCreateData(){
	
	$(".company-data").show();
	$(".personal-data").hide();
	
	// 类型
	$("input[name=cProxyType]").prop('checked',false);
	$("#cProxyType_1").prop('checked',true);
	$("#cCategoryId,#cProvinceId,#cCityId").val("");
	
	// 初始化文件选择相关
	$("#cIdentityBverseFile,#cIdentityReverseFile,#cBusinessLicenseFile").attr("data-url","");
	
	var objIB = document.getElementById('cIdentityBverseFile'); 
	objIB.outerHTML = objIB.outerHTML;
	$("#cFileDivIB").html("");
	
	var objIR = document.getElementById('cIdentityReverseFile'); 
	objIR.outerHTML = objIR.outerHTML;
	$("#cFileDivIR").html("");
	
	var objBL = document.getElementById('cBusinessLicenseFile'); 
	objBL.outerHTML = objBL.outerHTML;
	$("#cFileDivBL").html("");
}

/**
 * 确认创建
 */
function confirmCreateAgent() {
	// 获取参数
	var data = {};
	
	var proxyType = $("input[name='cProxyType']:checked").val();
	var isPCom = proxyType == "1" ? true : false;
	data['proxyType'] = proxyType;
	
	var name = $.trim($('#cName').val());
	if (Utils.isNull(name)) {
		showAlert('代理商名称不能为空!');
		return false;
	}
	data['name'] = name;
	
	var telephone = $.trim($('#cTelephone').val());
	if (Utils.isNull(telephone)) {
		showAlert("手机号不能为空!");
		return false;
	}else if (telephone.length != 11) {
		showAlert("手机号格式不正确，请检查!");
		return false;
	}
	data['telephone'] = telephone;
	
	var positionLimit = $.trim($('#cPositionLimit').val());
	if (Utils.isNull(positionLimit)) {
		showAlert("屏幕购买量不能为空!");
		return false;
	}else{
		if (positionLimit <= 0) {
			showAlert("屏幕购买量必须大于零!");
			return false;
		}
	}
	data['positionLimit'] = positionLimit;
	
	var categoryId = $.trim($('#cCategoryId').val());
	if (Utils.isNull(categoryId)) {
		showAlert("所属行业不能为空!");
		return false;
	}
	data['categoryId'] = categoryId;
	
	var cityId = $.trim($("#cCityId").val());
	if(Utils.isNull(cityId)){
		showAlert('请选择省市!');
		return false;
	}
	data['cityId'] = cityId;
	
	if(isPCom){
		var contacts = $.trim($('#cContacts').val());
		if (Utils.isNull(contacts)) {
			showAlert("联系人不能为空!");
			return false;
		}
		data['contacts'] = contacts;
		
		var businessLicenseFile = $("#cBusinessLicenseFile").attr("data-url");
		if(Utils.isNull(businessLicenseFile)){
			showAlert("请上传营业执照图!");
			return false;
	    }else{
			data['businessLicense'] = businessLicenseFile;
	    }
	}else{
		var identityBverseFile = $("#cIdentityBverseFile").attr("data-url");
		if(Utils.isNull(identityBverseFile)){
			showAlert("请上传身份证正面图!");
			return false;
	    }else{
	    	data['identityBverse'] = identityBverseFile;
	    }
	    
	    var identityReverseFile = $("#cIdentityReverseFile").attr("data-url");
		if(Utils.isNull(identityReverseFile)){
			showAlert("请上传身份证反面图!");
			return false;
	    }else{
			data['identityReverse'] = identityReverseFile;
	    }
	}
	
	var description = $.trim($('#cDescription').val());
	if (Utils.isNotNull(description)) {
		data['description'] = description;
	}
		
	// 调用接口
	var response = callInterface("post", "agent/createAgentCompany", data, false);
	if (response.code == 0) {
		showMsg('操作成功!');

		// 关闭对话框
		$('#createAgentDialog').modal("hide");

		// 刷新
		queryAgent();
	}
	else {
		showErrorMsg(response.code, response.message);
	}

	return false;
}

/**
 * 显示修改对话框
 */
function showModifyAgentDialog($id) {
	// 显示对话框
	$("#modifyAgentDialog").modal({
		backdrop : 'static',
		keyboard : false,
		show : true
	});
	$('#modifyAgentForm')[0].reset();
	$("#mId").val($id);
	// 获取详情
	getAgentDetail($id);
}

/**
 * 确认修改
 */
function confirmModifyAgent() {
	// 获取参数
	var data = {};
	data['id'] = $.trim($("#mId").val());
	
	var proxyType = $("input[name='mProxyType']:checked").val();
	var isPCom = proxyType == "1" ? true : false;
	data['proxyType'] = proxyType;
	
	var name = $.trim($('#mName').val());
	if (Utils.isNull(name)) {
		showAlert('代理商名称不能为空!');
		return false;
	}
	data['name'] = name;
	
	var telephone = $.trim($('#mTelephone').val());
	if (Utils.isNull(telephone)) {
		showAlert("手机号不能为空!");
		return false;
	}else if (telephone.length != 11) {
		showAlert("手机号格式不正确，请检查!");
		return false;
	}
	data['telephone'] = telephone;
	
	var positionLimit = $.trim($('#mPositionLimit').val());
	if (Utils.isNull(positionLimit)) {
		showAlert("屏幕购买量不能为空!");
		return false;
	}else{
		if (positionLimit <= 0) {
			showAlert("屏幕购买量必须大于零!");
			return false;
		}
	}
	data['positionLimit'] = positionLimit;
	
	var categoryId = $.trim($('#mCategoryId').val());
	if (Utils.isNull(categoryId)) {
		showAlert("所属行业不能为空!");
		return false;
	}
	data['categoryId'] = categoryId;
	
	var cityId = $.trim($("#mCityId").val());
	if(Utils.isNull(cityId)){
		showAlert('请选择省市!');
		return false;
	}
	data['cityId'] = cityId;
	
	if(isPCom){
		var contacts = $.trim($('#mContacts').val());
		if (Utils.isNull(contacts)) {
			showAlert("联系人不能为空!");
			return false;
		}
		data['contacts'] = contacts;
		
		var businessLicenseFile = $("#mBusinessLicenseFile").attr("data-url");
		if(Utils.isNull(businessLicenseFile)){
			showAlert("请上传营业执照图!");
			return false;
	    }else{
			data['businessLicense'] = businessLicenseFile;
	    }
	}else{
		var identityBverseFile = $("#mIdentityBverseFile").attr("data-url");
		if(Utils.isNull(identityBverseFile)){
			showAlert("请上传身份证正面图!");
			return false;
	    }else{
	    	data['identityBverse'] = identityBverseFile;
	    }
	    
	    var identityReverseFile = $("#mIdentityReverseFile").attr("data-url");
		if(Utils.isNull(identityReverseFile)){
			showAlert("请上传身份证反面图!");
			return false;
	    }else{
			data['identityReverse'] = identityReverseFile;
	    }
	}
	
	var description = $.trim($('#mDescription').val());
	if (Utils.isNotNull(description)) {
		data['description'] = description;
	}

	// 调用接口
	var response = callInterface("post", "agent/modifyAgentCompany", data, false);
	if (response.code == 0) {
		showMsg('操作成功!');

		// 关闭对话框
		$('#modifyAgentDialog').modal("hide");

		// 刷新
		queryAgent(currPage);
	}
	else {
		showErrorMsg(response.code, response.message);
	}
}

/**
 * 获取详情
 */
function getAgentDetail($id) {
	// 调用接口
	var response = callInterface("post", "agent/getAgentCompanyDetail", {
		'id' : $id
	}, false);
	if (response.code == 0) {
		var data = response.data;
		if (data != null) {
			$("#mId").val(data.id);
			$("#mName").val(data.name);
			$("#mTelephone").val(data.telephone);
			$("#mDescription").val(data.description);
			$("#mPositionLimit").val(data.positionLimit);
			$("input[name=mProxyType]").prop('checked',false);
			$("#mProxyType_"+data.proxyType).prop('checked',true);
			
			$("#mCategoryId").val(data.categoryId);
			$("#mProvinceId").val(data.provinceId);
			provinceChange('mProvinceId','mCityId',null);
			$("#mCityId").val(data.cityId);
			
			if(data.proxyType == "1"){
				$(".company-data").show();
				$(".personal-data").hide();
				$("#mContacts").val(data.contacts);
				
				// 初始化预览数据
				getImgPreHtml("mBusinessLicenseFile", fuIndex++, "mFileDivBL", true, null, data.businessLicense);
				$("#mBusinessLicenseFile").attr("data-url",data.businessLicense);
			}else{
				$(".company-data").hide();
				$(".personal-data").show();
				
				// 初始化预览数据
				getImgPreHtml("mIdentityBverseFile", fuIndex++, "mFileDivIB", true, null, data.identityBverse);
				$("#mIdentityBverseFile").attr("data-url",data.identityBverse);
				
				// 初始化预览数据
				getImgPreHtml("mIdentityReverseFile", fuIndex++, "mFileDivIR", true, null, data.identityReverse);
				$("#mIdentityReverseFile").attr("data-url",data.identityReverse);
			}
			updateLayuiForm();
		}
	}
	else {
		showErrorMsg(response.code, response.message);
	}
}

/**
 * 设置启用禁用
 */
function modifyAgentStatus(id) {
	var data = {};
	var status = 0;
	if($('#agent_status_'+id).is(":checked")){
		status = 1;
	}
	data.id = id;
	data.status = status;
	
	// 调用接口
	var response = callInterface("post", "agent/modifyAgentStatus", data, false);
	if (response.code == 0) {
		showMsg('操作成功!');
	} else {
		showErrorMsg(response.code, response.message);
	}
	return false;
}

function showResetPasswordDialog(userId, userName){
	// 显示对话框
	$("#resetPasswordDialog").modal({
		backdrop : 'static',
		keyboard : false,
		show : true
	});

	// 重置表单
	$('#resetPasswordForm')[0].reset();
	$("#rUserId").val(userId);
	$("#rUserName").html(userName);
}

/**
 * 重置密码
 */
function resetPassword() {
	// 获取数据
	var resetPassword = $.trim($('#resetPassword').val());
	if (Utils.isNull(resetPassword)) {
		showAlert('新密码不能为空!');
		return false;
	}
	
	var resetChkpwd = $.trim($('#resetChkpwd').val());
	if (Utils.isNull(resetChkpwd)) {
		showAlert('确认新密码不能为空!');
		return;
	}
	
	if (resetPassword != resetChkpwd) {
		showAlert('两次输入密码不一致!');
		return;
	}
	
	// 设置参数
	var $data = {
		"id" : $.trim($("#rUserId").val()),
		"newPassword" : $.md5(resetPassword)
	}

	// 调用接口
	var response = callInterface("post", "agent/resetAgentPassword", $data, false);
	if (response.code == 0) {
		showMsg('操作成功!');
		$('#resetPasswordDialog').modal("hide");
	}
	else {
		showErrorMsg(response.code, response.message);
	}
}

